// src/api/newsApi.js

import axios from 'axios';

export const $fetchFinanceNews = (params = {}) => {
  // 定义多个新闻源的API路径
  const newsSources = [
    '/api/news/sina',
    '/api/news/pbc',
  ];

  // 并发请求多个新闻源
  const requests = newsSources.map(source => 
    axios.get(source, { params })
      .then(response => {
        // 确保响应数据格式统一
        console.log(`响应数据(${source}):`, response.data);
        if (response.data && typeof response.data.code !== 'undefined') {
          return response.data;
        }
        return {
          code: 0,
          data: response.data || [],
          total: response.data?.length || 0
        };
      })
      .catch(error => {
        console.error(`请求失败(${source}):`, error);
        return {
          code: -1,
          data: [],
          total: 0
        };
      })
  );

  // 使用Promise.all并发请求所有新闻源
  return Promise.all(requests)
    .then(results => {
      // 合并所有新闻源的结果
      const mergedData = results.reduce((acc, result) => {
        if (result.code === 0) {
          acc.data = acc.data.concat(result.data);
          acc.total += result.total;
        }
        return acc;
      }, { code: 0, data: [], total: 0 });

      return mergedData;
    });
};

export const $refreshNews = () => {
  return axios.post('/news/refresh');
};

